#!/bin/bash
TOP_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/../.." &> /dev/null && pwd )"
CUR_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

PACKAGE_MANAGER=$((command -v apt-get > /dev/null && echo apt-get) \
    || (command -v yum > /dev/null && echo yum) \
    || (echo "Neither apt-get nor yum is installed, please install one of them first." && exit 1))
#package mirros & docker images mirrors
#linux软件镜像站，可自行选取
#ustc 中科大
#DEFAULT_PKG_MIRROR=https://mirrors.ustc.edu.cn
#tsinghua 清华
#DEFAULT_PKG_MIRROR=https://mirrors.tuna.tsinghua.edu.cn
#aliyun 阿里云
DEFAULT_PKG_MIRROR="https://mirrors.aliyun.com"
#163 网易
#DEFAULT_PKG_MIRROR=http://mirrors.163.com
#tecent 腾讯
#DEFAULT_PKG_MIRROR=http://mirrors.cloud.tencent.com

DOWNLOAD_DIR=$CUR_DIR/package

##include scripts##
##include end##

# Remove any lock files that may be preventing package manager from running.
# 删除可能阻止包管理器运行的任何锁定文件
clean_locks() {
    if [ "$PACKAGE_MANAGER" == "apt-get" ]; then
        rm -rf /var/lib/dpkg/lock
        rm -rf /var/lib/dpkg/lock-frontend
        rm -rf /var/cache/apt/archives/lock
    elif [ "$PACKAGE_MANAGER" == "yum" ]; then
        rm -rf /var/run/yum.pid
        rm -rf /var/run/yum.pid.old
        # rm -rf /var/cache/yum/*
    fi
}
delete_old_version() {
    echo "Delete version ..."

    clean_locks
    if [ "$PACKAGE_MANAGER" == "apt-get" ]; then
        local pkgs=$(dpkg -l | grep -E 'ebtables' | awk '{print $2}')
        if [ -n "$pkgs" ] ; then
            set -x
            apt-get remove -y $pkgs > /dev/null 2>&1
            apt-get autoremove -y > /dev/null
            apt-get autoclean -y > /dev/null
            set +x
        fi
    elif [ "$PACKAGE_MANAGER" == "yum" ]; then
        local pkgs=$(rpm -qa | grep -E 'ebtables' | awk '{print $1}')
        if [ -n "$pkgs" ] ; then
            set -x
            yum remove -y $pkgs > /dev/null 2>&1
            yum autoremove -y > /dev/null
            yum clean all > /dev/null
            set +x
        fi
    fi
}

download_pkg() {
    if [ "$PACKAGE_MANAGER" == "apt-get" ]; then
        apt install ebtables -y -d -o=dir::cache::archives=$DOWNLOAD_DIR --reinstall  > /dev/null 2>&1
	    rm -rf $DOWNLOAD_DIR/lock
	    rm -rf $DOWNLOAD_DIR/partial
    elif [ "$PACKAGE_MANAGER" == "yum" ]; then
	    yum install ebtables -y 
	fi
}

# install ebtables components online.
# 在线安装 ebtables 组件。
install_ebtables() {
    clean_locks
    if [ ! -d $DOWNLOAD_DIR ]; then
	    mkdir -p $DOWNLOAD_DIR
        download_pkg
    fi
    set -x
	if [ "$PACKAGE_MANAGER" == "apt-get" ]; then
        dpkg -i $DOWNLOAD_DIR/*.deb
	elif [ "$PACKAGE_MANAGER" == "yum" ]; then
	    yum install -y $DOWNLOAD_DIR/*.rpm
	fi
    hash -r
    ebtables --version
    set +x
}

clean_download() {
    rm -rf $DOWNLOAD_DIR
}
function print_usage() {
    echo "Usage: $0 [--rm|--remove] [--clean|-c] [--downloadonly|-d] []"
    echo "Options:"
    echo "  --rm|--remove: uninstall ebtables"
    echo "  --clean|-c: remove downloaded files"
    echo "  --downloadonly|-d: only download ebtables package, do not install"
	echo "  --pkg-mirror=<https://xxx>: specify the pkg mirror to be used, default is https://mirrors.ustc.edu.cn"
    echo "         eg: 1, https://mirrors.ustc.edu.cn"
    echo "             2, https://mirrors.tuna.tsinghua.edu.cn"
    echo "             3, https://mirrors.aliyun.com"
    echo "             4, http://mirrors.163.com"
    echo "             5, http://mirrors.cloud.tencent.com"
    echo "  example1, download pkg: "
    echo "          ./install.sh --downloadonly"
    echo "  example2, install pkg, and then clean binary pkg" 
    echo "         ./install.sh --clean"
}

#
#=====================main func ==============================
if [[ $EUID -ne 0 ]]; then
    echo "This script must be run as root"
    exit 1
fi

#清除旧版本的影响，保证command -v命令得到正确的结果
hash -r

ARGS=$#
# Parse command line arguments
while [[ $# -gt 0 ]]
do
    key="$1"
    case $key in
	--online|-o)
        ONLINE=true
        shift
        ;;
    --force|-f)
        FORCE=true
        shift
        ;;
    --clean|-c)
        if [[ $ARGS -eq 1 ]]; then
            clean_download
            exit 0
        fi
        AUTOCLEAN=true
        shift
        ;;
    --downloadonly|-d)
        DOWNLOAD_ONLY=true
        shift
        ;;
    --pkg-mirror=*)
        PKG_MIRROR="${key#*=}"
        shift
        ;;
    --pkg-mirror)
        shift
        PKG_MIRROR="$1"
        shift
        ;;
    --help)
        print_usage
        exit 1
        ;;
    --rm|--remove)
        echo "ebtables components uninstall..."
        delete_old_version
        exit 1
        ;;
    -[^-]*)
        for ((i=1; i<${#key}; i++)); do
          case "${key:$i:1}" in
		    o) ONLINE=true ;;
            f) FORCE=true ;;
            c) AUTOCLEAN=true ;;
            d) DOWNLOAD_ONLY=true ;;
            *) print_usage; exit 1 ;;
          esac
        done
        shift    
        ;;
    *)    # unknown option
        print_usage
        exit 1
        ;;
    esac
done

PKG_MIRROR=${PKG_MIRROR:-$DEFAULT_PKG_MIRROR}
DOWNLOAD_ONLY=${DOWNLOAD_ONLY:-false}
AUTOCLEAN=${AUTOCLEAN:-false}

#设置软件安装源，从而获得最新版本
echo "downloadonly=$DOWNLOAD_ONLY pkg-mirror=$PKG_MIRROR autoClean=$AUTOCLEAN"
if $DOWNLOAD_ONLY ; then
    download_pkg
    exit 0
fi

[ -n "$CURRENT_VERSION" ] && delete_old_version

echo "Install version $TARGET_VERSION ..."
install_ebtables

$AUTOCLEAN && clean_download


